import { defineStore } from 'pinia';
import { Notification } from '@arco-design/web-vue';
import type { NotificationReturn } from '@arco-design/web-vue/es/notification/interface';
import type { RouteRecordRaw } from 'vue-router';
import defaultSettings from '@/config/settings.json';
import { getMenuList } from '@/api/user';
import { AppState } from './types';

const globalViews = import.meta.glob('@/views/**/**.vue');
function requireComponent(componentPath: string) {
  const viewPath = `/src/views/${componentPath}.vue`;
  console.log(viewPath, globalViews[viewPath]);
  try {
    if (globalViews[viewPath]) {
      return globalViews[viewPath]();
    } else {
      console.warn(`Component not found: ${componentPath}`);
      return import('@/views/error/404.vue');
    }
  } catch (error) {
    console.error(`Failed to load component: ${componentPath}`, error);
    return import('@/views/error/404.vue');
  }
}

function loadComponent(componentPath: string): () => Promise<any> {
  if (componentPath === 'Layout') {
    return () => import('@/layout/default-layout.vue');
  }
  if (componentPath === 'ParentView') {
    return () => import('@/components/parent-view/index.vue');
  }
  if (typeof componentPath === 'string') {
    return () => requireComponent(componentPath);
  }
  return componentPath;
}
function transformRoutes(routes: any[]): RouteRecordRaw[] {
  const transformedRoutes = routes
    .filter((route) => route.path && !route.path.startsWith('http'))
    .map((route) => {
      console.log('route.component', route.component);
      const transformedRoute: any = {
        ...route,
        component: route.component ? loadComponent(route.component) : undefined,
      };
      if (route.children && route.children.length > 0) {
        transformedRoute.children = transformRoutes(route.children);
      }

      return transformedRoute;
    });

  return transformedRoutes;
}

const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordRaw[] {
      return state.serverMenu as unknown as RouteRecordRaw[];
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    async fetchServerMenuConfig() {
      let notifyInstance: NotificationReturn | null = null;
      try {
        notifyInstance = Notification.info({
          id: 'menuNotice', // Keep the instance id the same
          content: 'loading',
          closable: true,
        });
        const res = await getMenuList();
        const formatterMenus = transformRoutes(res.data);
        this.serverMenu = formatterMenus;
        notifyInstance = Notification.success({
          id: 'menuNotice',
          content: 'success',
          closable: true,
        });
        return res.data;
      } catch (error) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        notifyInstance = Notification.error({
          id: 'menuNotice',
          content: 'error',
          closable: true,
        });
        return false;
      }
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useAppStore;
